const mongoose = require('mongoose')
    //数据库地址
const url = 'mongodb://localhost/smile-vue'

const db = mongoose.connect


exports.connect = () => {
    mongoose.set('useCreateIndex', true)

    //连接数据库
    db(url, { useNewUrlParser: true, useUnifiedTopology: true })
        // 定义数据库连接变量
    let maxConnectTime = 0

    return new Promise((resolve, reject) => {
        //增加数据库监听事件  当Mongoose成功建立到MongoDB服务器的初始连接时发出
        mongoose.connection.on('disconnected', (err) => {
            console.log('***********数据库断开***********')
            if (maxConnectTime <= 3) {
                maxConnectTime++
                db(url, { useNewUrlParser: true, useUnifiedTopology: true })
            } else {
                reject(err)
                throw new Error('数据库出现问题，程序无法搞定，请人为修理.....')
            }

        })
        mongoose.connection.on('error', (err) => {
            console.log('数据库连接失败')
            if (maxConnectTime <= 3) {
                maxConnectTime++
                db(url, { useNewUrlParser: true, useUnifiedTopology: true })
            } else {
                reject(err)
                throw new Error('数据库出现问题，程序无法搞定，请人为修理.....')
            }

        })
        mongoose.connection.once('open', () => {
            console.log('数据库连接成功')
            resolve()
        })
    })
}